//
//  WTPublishCommentViewController.m
//  OneDay
//
//  Created by lanou on 16/1/22.
//  Copyright © 2016年 小明. All rights reserved.
//

#import "WTPublishCommentViewController.h"
#import "WTSquareHeadView.h"
#import "WTRequestManager.h"
#import "WTInformationHandle.h"

@interface WTPublishCommentViewController ()<UITextViewDelegate,UITextFieldDelegate>


// 自定义导航栏
@property (nonatomic, strong) WTSquareHeadView * headView;

// 内容的textView
@property (nonatomic, strong) UITextView * contentTV;
@end

@implementation WTPublishCommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
//    _contentTV = [[UITextView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenWidth - 64)];
    _contentTV = [[UITextView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, 200)];
    _contentTV.delegate = self;
    _contentTV.font = [UIFont systemFontOfSize:16];
    _contentTV.returnKeyType = UIReturnKeyNext;
    [self.view addSubview:_contentTV];
    [_contentTV becomeFirstResponder];
  
    [self addHeadView];
    //增加监听，当键盘出现或改变时收出消息
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)name:UIKeyboardWillShowNotification
     object:nil];
    
// Do any additional setup after loading the view.
}

// 当键盘出现或改变时调用

- (void)keyboardWillShow:(NSNotification *)aNotification

{
    
    //获取键盘的高度
    
    NSDictionary *userInfo = [aNotification userInfo];
    
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect = [aValue CGRectValue];
    
    int height = keyboardRect.size.height;
    
    _contentTV.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64 - height);
}

#pragma mark -- 自定义导航栏
- (void)addHeadView
{
  
    _headView = [[WTSquareHeadView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    _headView.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_headView];
    
    [_headView.leftButton setBackgroundImage:[UIImage imageNamed:@"m-fanhui"] forState:(UIControlStateNormal)];
    [_headView.leftButton addTarget:self action:@selector(backButton:) forControlEvents:(UIControlEventTouchUpInside)];
    _headView.titleLabel.text = @"发表评论";
    [_headView.rightButton setTitle:@"发表" forState:(UIControlStateNormal)];
    [_headView.rightButton addTarget:self action:@selector(publishButton:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)backButton:(UIButton *)button
{
    [self.view endEditing:YES];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)publishButton:(UIButton *)button
{
    [self.view endEditing:YES];
    
//     fid=671&tid=1928969&uid=1174939&subject=%E4%B8%8B%E9%9B%AA%E4%BA%86+%E6%9C%89%E7%82%B9%E5%86%B7%E4%BA%86&message=%E3%80%82%E3%80%82%E3%80%82%E3%80%82&username=181****5323&act=1&plat=android&proct=mierapp&versioncode=20160112&apiCode=6
    NSMutableDictionary * parDic = [NSMutableDictionary dictionary];
    parDic[@"fid"] = _fid;
    parDic[@"tid"] = _tid;
    parDic[@"username"] = [WTInformationHandle shareInformationHandle].userName;
    NSLog(@"%@",[WTInformationHandle shareInformationHandle].ID);
    parDic[@"uid"] = [WTInformationHandle shareInformationHandle].ID;
    parDic[@"versioncode"] = @"20160112";
    parDic[@"act"] = @"1";
    parDic[@"plat"] = @"android";
    parDic[@"proct"] = @"mierapp";
    parDic[@"message"] = _contentTV.text;
    parDic[@"apiCode"] = @"6";
    
    [WTRequestManager requestWithUrlString:@"http://bbs.mier123.com/api/quanzi/post_reply.php?plat=android&proct=mierapp&versioncode=20160112" parDic:parDic method:POST success:^(NSData *data) {
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dic);
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:dic[@"msg"] preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction * okAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"COMMENT" object:self userInfo:nil];
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
        [alert addAction:okAction];
        
       
        
        [self presentViewController:alert animated:YES completion:nil];
        

    } error:^(NSError *error) {
    }];
}



#pragma mark -- 在文本框内容发生变化时计算所有文字的长度,判断是否超过
-(void)textViewDidChange:(UITextView *)textView
{
    NSDictionary *dict1=@{NSFontAttributeName:[UIFont systemFontOfSize:16]};
    CGSize contentSize1=[@"我" sizeWithAttributes:dict1];
    CGFloat heightText=contentSize1.height;
    
    
    float currentLineNum=1;//默认文本框显示一行文字
    float textViewWidth=_contentTV.frame.size.width;//取得文本框高度
    NSString *content=textView.text;
    NSDictionary *dict=@{NSFontAttributeName:[UIFont systemFontOfSize:16]};
  
    CGSize contentSize=[content sizeWithAttributes:dict];//计算文字长度
//    if (contentSize.height <= _contentTV.height) {
//        contentSize = CGSizeMake(contentSize.width, _contentTV.height);
//    }
//    
    
    float numLine=ceilf(contentSize.width/textViewWidth); //计算当前文字长度对应的行数
    
    if(numLine>currentLineNum ){
        //如果发现当前文字长度对应的行数超过。 文本框高度，则先调整当前view的高度和位置，然后调整输入框的高度，最后修改currentLineNum的值
//        _keyAssistView.frame=CGRectMake(_keyAssistView.left, _keyAssistView.top - _heightText*(numLine-currentLineNum), _keyAssistView.width, _keyAssistView.height+ _heightText*(numLine-currentLineNum));
        textView.frame=CGRectMake(textView.left, textView.top, textView.width, textView.height+heightText*(numLine-currentLineNum));
        currentLineNum=numLine;
    }else if (numLine<=currentLineNum ){
        //次数为删除的时候检测文字行数减少的时候
//        _keyAssistView.frame=CGRectMake(_keyAssistView.left, _keyAssistView.top +_heightText*(currentLineNum-numLine),_keyAssistView.width, _keyAssistView.height-_heightText*(currentLineNum-numLine));
//        textView.frame=CGRectMake(textView.left, textView.top, textView.width, textView.height-heightText*(numLine-currentLineNum));
//        currentLineNum=numLine;
    }
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
